const handleError = require('../utils/error/handle')
const ErrorCode = require('../utils/error/code')

module.exports = async function(ctx, next) {
	delete ctx.request.headers['content-encoding']
	try {
		await next()
	}
	catch (error) {
		console.log(error)

		let response

		if (typeof (error) === 'number') {
			if (ErrorCode[error] !== undefined) {
				response = {
					responseCode    : error,
					responseMessage : ErrorCode[error],
					parameters      : {
						requestId : ctx.requestId
					}
				}
			}
			else {
				response = {
					responseCode    : 500,
					responseMessage : '未定义的错误',
					parameters      : {
						requestId : ctx.requestId
					}
				}
			}
		}
		else {
			response = {
				responseCode    : 500,
				responseMessage : handleError(error),
				parameters      : {
					requestId : ctx.requestId
				}
			}
		}

		ctx.body = response

		// await global.db.apiLogModel.updateOne({ id : ctx.requestId }, {
		// 	$set : {
		// 		done    : true,
		// 		resBody : response,
		// 		error   : error
		// 	}
		// })

		return

	}
}
